package controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import model.TaskManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.DataSetObserver;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import app.cloudstringers.R;
import define.API;
import define.Constants;
import define.Key;

/**
 * Apply only for Upload class and Convert class
 * 
 * @author Administrator
 * 
 */
public class GetTaskManagerAsync extends AsyncTask<String, Void, Boolean> {
	/**
	 * String section
	 */
	private boolean IS_NO_NEW_TASK = false;
	
	// All static variables
	private static final String KEY_TASK_DESCRIPTION = "task_description";
	private static final String KEY_TASK_DURATION = "task_duration";
	private static final String KEY_TASK_ID = "taskId";
	private static final String KEY_TASK_NAME = "task_name";
	private static final String KEY_TASK_START_DATE_TIME = "task_start_date_time";
	private static final String KEY_TASK_STATUS = "task_status";
	private static final String KEY_TASK_TIMEZONE_IN_GMT = "task_timezone_in_gmt";

	private String DESCRIPTION = null, DURATION = null, ID = null, NAME = null,
			START_DATE_TIME = null, STATUS = null, TIMEZONE_IN_GMT = null;

	private String GLOBAL_ID = null;
	
	private static String NO_NEW_TASK = null;
	
	private static final String TAG = GetTaskManagerAsync.class.getSimpleName();

	/**
	 * Data section
	 */
	private LinkedList<TaskManager> mLlTaskManger = new LinkedList<TaskManager>();
	private TaskManagerItemAdapter adapter = null;

	/**
	 * Listener section
	 */
	private OnClickListener mListenerCancel = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (mDialog.isShowing()) {
				mDialog.dismiss();
			}
		}
	};

	/**
	 * View section
	 */
	private Dialog mDialog;
	private ImageButton mIbtnCancel;
	private ListView mLv;
	private TextView mTvDescription;
	private TextView mTvDuration;
	private TextView mTvState;
	private TextView mTvTimeZone;

	/**
	 * Others section
	 */
	private Context context;

	public GetTaskManagerAsync(Context context) {
		this.context = context;

		NO_NEW_TASK = context.getString(R.string.no_new_task);
		
		/**
		 * Should create new adapter in here, not in Background Thread
		 * to avoid crash was happened sometimes
		 */
		adapter = new TaskManagerItemAdapter(
				context, R.layout.simple_list_item_task_manager, mLlTaskManger);
	}

	@Override
	protected Boolean doInBackground(String... params) {
		// Set data
		GLOBAL_ID = params[0];

		/**
		 * Call Status API to show the files in List View
		 */
		HttpClient mHttpClient = new DefaultHttpClient();
		HttpPost mHttpPost = new HttpPost(API.TASK_LIST_REQUEST);
		List<NameValuePair> mNv = new ArrayList<NameValuePair>(2);

		mNv.add(new BasicNameValuePair(Key.KEY_USER_ID, GLOBAL_ID));
		mNv.add(new BasicNameValuePair(Key.KEY_TASK_REQUEST, Key.KEY_VIEW));

		try {
			mHttpPost.setEntity(new UrlEncodedFormEntity(mNv));
			HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
			HttpEntity mHttpEntity = mHttpResponse.getEntity();

			String XML = EntityUtils.toString(mHttpEntity);

			/**
			 * If no new task in here, need show dialog inform to user
			 */
			if (XML.contains(NO_NEW_TASK)) {
				IS_NO_NEW_TASK = true;
				return false;
			}
			
//			Log.i(TAG, XML);
			
			/**
			 * Begin split key to get data
			 */
			JSONObject mJoParent = new JSONObject(XML);
			Iterator<?> iterator = mJoParent.keys();
			while (iterator.hasNext()) {
				String KEY = (String) iterator.next();
				JSONObject mJoChild = mJoParent.getJSONObject(KEY);

				// Data
				DESCRIPTION = mJoChild.optString(KEY_TASK_DESCRIPTION);
				DURATION = mJoChild.optString(KEY_TASK_DURATION);
				ID = mJoChild.optString(KEY_TASK_ID);
				NAME = mJoChild.optString(KEY_TASK_NAME);
				START_DATE_TIME = mJoChild.optString(KEY_TASK_START_DATE_TIME);
				STATUS = mJoChild.optString(KEY_TASK_STATUS);
				TIMEZONE_IN_GMT = mJoChild.optString(KEY_TASK_TIMEZONE_IN_GMT);

				// Add data object into array
				TaskManager taskManager = new TaskManager(DESCRIPTION, DURATION, 
						ID, NAME, START_DATE_TIME, STATUS, TIMEZONE_IN_GMT);
				mLlTaskManger.add(taskManager);
			}

			return true;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return false;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		Constants.utils.showProgressDialog();

		// Clear data first before use new data
		if (mLlTaskManger != null && !mLlTaskManger.isEmpty()) {
			mLlTaskManger.clear();
		}

		mLv = (ListView) ((Activity) context).findViewById(R.id.lv_in_task_manager);
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);

		if (!result) {
			if (IS_NO_NEW_TASK) {
				showNoItemDialog(context);
			} else {
				Class<?> object = null;
				try {
					object = Class.forName(context.getClass().getName());
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}

				Constants.utils.showConnectionTimeoutDialog(context, object);
			}
		} else {
			if (adapter != null & !adapter.isEmpty()) {
				// If the server responses data
				// Set adapter for list
				mLv.setAdapter(adapter);
				// Notify user that data has already changed
				adapter.notifyDataSetChanged();
			} else if (adapter != null & adapter.isEmpty()) {
				// If the server responses null data
				// refresh to see null page
				mLv.setAdapter(adapter);
				// Notify user that data has already changed
				adapter.notifyDataSetChanged();

				adapter = null;
			}
		}
		
		Constants.utils.hideProgressDialog();
	}

	/**
	 * Initialize methods
	 */

	private void initialData(int position) {
		mIbtnCancel.setOnClickListener(mListenerCancel);

		mTvDescription.setText(mLlTaskManger.get(position).getDescription());
		mTvDuration.setText(mLlTaskManger.get(position).getDuration());
		mTvState.setText(mLlTaskManger.get(position).getState());
		mTvTimeZone.setText(mLlTaskManger.get(position).getTimeZone());
	}

	private void initalVariables(Dialog d) {
		mIbtnCancel = (ImageButton) d
				.findViewById(R.id.ibtn_cancel_in_task_manager_info);
		mTvDescription = (TextView) d
				.findViewById(R.id.tv_description_in_task_manager_info);
		mTvDuration = (TextView) d
				.findViewById(R.id.tv_duration_in_task_manager_info);
		mTvState = (TextView) d
				.findViewById(R.id.tv_state_in_task_manager_info);
		mTvTimeZone = (TextView) d
				.findViewById(R.id.tv_time_zone_in_task_manager_info);
	}

	/**
	 * Basic methods
	 */
	/**
	 * Show Exit dialog
	 */
	public static void showNoItemDialog(Context context) {
		new AlertDialog.Builder(context)
		.setTitle(R.string.task_manager)
		.setCancelable(true)
		.setMessage(NO_NEW_TASK.substring(0, 1).toUpperCase()
				+ NO_NEW_TASK
				.substring(1, NO_NEW_TASK.length()).toLowerCase())
		.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9,
					int whichButton) {
			}
		}).show();
	}
	
	/**
	 * Class
	 * @author trek2000
	 *
	 */
	public class TaskManagerItemAdapter extends ArrayAdapter<TaskManager> {
		/**
		 * String section
		 */
		private int textViewResourceId;
		private String TAG_STATUS = "status_";
		private String TAG_TASK = "task_";

		/**
		 * Data section
		 */
		private LinkedList<TaskManager> mLlItems = new LinkedList<TaskManager>();

		/**
		 * View section
		 */
		private class ViewHolder {
			private ImageButton mIbtnState;
			private LinearLayout mLlTask;
			private TextView mTvName;
			private TextView mTvStartDateTime;
		}
		
		/**
		 * Listener section
		 */
		private OnClickListener mListenerShowDialog = new OnClickListener() {

			@Override
			public void onClick(View v) {
				/**
				 * Show info dialog
				 */
				mDialog = new Dialog(context);
				mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				mDialog.setContentView(R.layout.dialog_task_manager_info);

				initalVariables(mDialog);
				initialData(mLv.getPositionForView(v));
				
				Constants.utils.initialFullWidthScreenDialog(mDialog);
				mDialog.show();			
			}
		};
		
		/**
		 * The others section
		 */
		private Context context;

		public TaskManagerItemAdapter(Context context,
				int textViewResourceId, LinkedList<TaskManager> mLlItems) {
			super(context, textViewResourceId, mLlItems);

			this.context = context;
			this.textViewResourceId = textViewResourceId;
			this.mLlItems = mLlItems;
		}

		@Override
		public View getView(final int position, View v, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (v == null) {
				viewHolder = new ViewHolder();
				LayoutInflater mLiInflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

				v = mLiInflater.inflate(textViewResourceId, null);

				// Initial variables
				viewHolder.mLlTask = (LinearLayout) v
						.findViewById(R.id.ll_task_manager);
				viewHolder.mIbtnState = (ImageButton) v
						.findViewById(R.id.ibtn_item_in_task_manager);
				viewHolder.mTvName = (TextView) v
						.findViewById(R.id.tv_name_in_task_manager);
				viewHolder.mTvStartDateTime = (TextView) v
						.findViewById(R.id.tv_start_date_time_in_task_manager);
				
				// Set tag
				viewHolder.mIbtnState.setTag(TAG_STATUS + position);
				viewHolder.mLlTask.setTag(TAG_TASK + position);
				
				v.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) v.getTag();

				// Set tag
				viewHolder.mIbtnState.setTag(TAG_STATUS + position);
				viewHolder.mLlTask.setTag(TAG_TASK + position);
			}

			// Set Listener
			viewHolder.mLlTask.setOnClickListener(mListenerShowDialog);
			
			// Set data for name and start date time
			viewHolder.mTvName.setText(mLlItems.get(position).getName());
			viewHolder.mTvStartDateTime.setText(mLlItems.get(position)
					.getStartDateTime());

			// Set data for image button
			/**
			 * Status = "a" : Start button;
			 * Status = "p" : Accepted text;
			 * Status = "d" : Not Accepted text;
			 * Status = "e" : Start button;
			 * Status = "s" : End button
			 */
			getData(viewHolder, position);

			/**
			 * Set On click listener to update the request
			 */
			viewHolder.mIbtnState.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					updateData(v, position);
				}
			});

			return v;
		}

		private void getData(ViewHolder viewHolder, int position) {
			if (mLlItems.get(position).getState()
					.equals(define.TaskManager.A)) {
				/**
				 * Start state
				 */
				viewHolder.mIbtnState.findViewWithTag(TAG_STATUS + position)
				.setBackgroundResource(R.drawable.ibtn_play_state_normal);
			} else if (mLlItems.get(position).getState()
					.equals(define.TaskManager.D)) {
				/**
				 * Not accepted state
				 */
				viewHolder.mIbtnState.findViewWithTag(TAG_STATUS + position)
				.setBackgroundResource(R.drawable.ibtn_not_accepted_normal);
			} else if (mLlItems.get(position).getState()
					.equals(define.TaskManager.E)) {
				/**
				 * Start state
				 */
				viewHolder.mIbtnState.findViewWithTag(TAG_STATUS + position)
				.setBackgroundResource(R.drawable.ibtn_play_state_normal);
			} else if (mLlItems.get(position).getState()
					.equals(define.TaskManager.P)) {
				/**
				 * Accepted state
				 */
				viewHolder.mIbtnState.findViewWithTag(TAG_STATUS + position)
				.setBackgroundResource(R.drawable.ibtn_accept_normal);
			} else if (mLlItems.get(position).getState()
					.equals(define.TaskManager.S)) {
				/**
				 * End state
				 */
				viewHolder.mIbtnState.findViewWithTag(TAG_STATUS + position)
				.setBackgroundResource(R.drawable.ibtn_stop_state_normal);
			}  			
		}

		@Override
		public void unregisterDataSetObserver(DataSetObserver observer) {
			if (observer != null) {
				super.unregisterDataSetObserver(observer);
			}
		}

		/**
		 * Basic methods
		 */
		private void updateData(View v, int position) {
			if (mLlItems.get(position).getState().equals(define.TaskManager.A) 
					| mLlItems.get(position).getState().equals(define.TaskManager.E)) {
				// Play button
				new UpdateTaskManagerAsync(context).execute(GLOBAL_ID, 
						mLlItems.get(position).getID(), define.TaskManager.S);
			} else if (mLlItems.get(position).getState().equals(define.TaskManager.S)) {
				// Stop button
				new UpdateTaskManagerAsync(context).execute(GLOBAL_ID, 
						mLlItems.get(position).getID(), define.TaskManager.E);
			} else {
				/**
				 * Disable button if received inappropriate message 
				 */
				v.setEnabled(false);
			}
		}
	}
}
